package com.fosun.spr.core.resolver;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import com.fosun.spr.core.base.model.CoBaseSrModel;
import com.fosun.spr.core.constants.BaseConstants;
import com.fosun.spr.core.exception.ServiceException;
import com.fosun.spr.core.message.ResultCode;
import com.fosun.spr.core.proxy.aop.BaseAspect;
 

/**
 * 
 * @Title: WholeExceptionResolver.java
 * @Description: 自定义异常
 * @author zhangcheng
 * @date 2017年3月7日 下午6:15:55
 * @version V1.0
 * 
 */
public class WholeExceptionResolver extends BaseAspect implements
		HandlerExceptionResolver {

	public ModelAndView resolveException(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception e) {
		
		resCodeResolver(response, e);
		return new ModelAndView();
	}

	/**
	 * 
	 * @Title: selfResolver
	 * @Description: 处理自定义异常/内部异常
	 * @param e
	 *            捕捉的异常
	 * @return String
	 */
	private void resCodeResolver(HttpServletResponse response,Exception e) {
		e.printStackTrace();
		CoBaseSrModel coBaseSrModel = null;
		if (e instanceof ServiceException) {// 自定义异常类
			ServiceException se = (ServiceException) e;
			String code = !StringUtils.isBlank(se.getCode()) ? se.getCode()
					: ResultCode.SERVER_INNER_ERROR.getCode();
			String msg = !StringUtils.isBlank(se.getMessage()) ? se
					.getMessage() : ResultCode.SERVER_INNER_ERROR.getMessage();
			coBaseSrModel = new CoBaseSrModel(code, msg);
		} else {// 其它异常（系统内部异常、业务处理）
			// TODO
			// 2.发送邮件警告
			// 3.请求数量多可以采用异步队列推送方式
			coBaseSrModel = new CoBaseSrModel(
					ResultCode.SERVER_INNER_ERROR.getCode(),
					ResultCode.SERVER_INNER_ERROR.getMessage());
		}
		
		try {
			returnStyle(response);// 设置返回格式
			response.getWriter().write(coBaseSrModel.toString());
		} catch (IOException ioe) {
			ioe.printStackTrace();
		}
	}

	private void returnStyle(HttpServletResponse response) {
		response.setStatus(HttpStatus.OK.value());
		response.setContentType(MediaType.APPLICATION_JSON_VALUE);
		response.setCharacterEncoding(BaseConstants.UTF_8);
		response.setHeader(BaseConstants.CACHE_KEY, BaseConstants.CACHE_VAL);
	}

}
